#include "seriallogic.h"

SerialLogic::SerialLogic(QObject *parent) : QThread(parent)
{
    memset(status,0,sizeof (int));
    setParent(parent);
    exit=false;
}

SerialLogic::~SerialLogic()
{
    exit=true;
}

#include <iostream>
void SerialLogic::setAlarmMode(bool model)
{    
    this->model=model;    
    one=1;tow=0;
}

void SerialLogic::startSlave(const QString &portName1,  const QString &portName2, int channel)
{
    portName.append(portName1);
    portName.append(portName2);
    this->channel=channel;

    if(!isRunning())
    {
        start();
    }
}

void SerialLogic::run()
{
    QSerialPort serial1;
    QSerialPort serial2;

    //COM1
    serial1.close();
    serial1.setPortName(portName[0]);

    if (!serial1.open(QIODevice::ReadWrite))
    {
        emit message(tr("Can't open %1, error code %2").arg(portName[0]).arg(serial1.error()));
        return;
    }

    //设置DTR电平高
    if(serial1.setDataTerminalReady(true))
    {
        emit message(tr("set DataTerminalReady successful"));
    }
    else
    {
        emit message(tr("Can't set DTR  %1, error code %2").arg(portName[0]).arg(serial1.error()));
        return;
    }
    //设置RTS电平高,可以不设置
    if(serial1.setRequestToSend(true))
    {
        emit message(tr("set RequestToSend successful"));
    }
    else
    {
        emit message(tr("Can't set RTS  %1, error code %2").arg(portName[0]).arg(serial1.error()));
    }

    //COM2
    serial2.close();
    serial2.setPortName(portName[1]);

    if (!serial2.open(QIODevice::ReadWrite))
    {
        emit message(tr("Can't open %1, error code %2").arg(portName[1]).arg(serial2.error()));
        return;
    }

    //设置DTR电平高
    if(serial2.setDataTerminalReady(true))
    {
        emit message(tr("set DataTerminalReady successful"));
    }
    else
    {
        emit message(tr("Can't set DTR  %1, error code %2").arg(portName[1]).arg(serial2.error()));
        return;
    }
    //设置RTS电平高,可以不设置
    if(serial2.setRequestToSend(true))
    {
        emit message(tr("set RequestToSend successful"));
    }
    else
    {
        emit message(tr("Can't set RTS  %1, error code %2").arg(portName[1]).arg(serial2.error()));
    }

    //循环逻辑判断
    while (!this->exit)
    {
        this->usleep(1);

        //COM1
        //A1
        status[0]= (serial1.pinoutSignals()&QSerialPort::ClearToSendSignal)?one:tow;
        //A2
        status[1]= (serial1.pinoutSignals()&QSerialPort::DataSetReadySignal)?one:tow;
        //D1
        status[2]= (serial1.pinoutSignals()&QSerialPort::DataCarrierDetectSignal)?one:tow;

        //COM2
        //B1
        status[3]= (serial2.pinoutSignals()&QSerialPort::ClearToSendSignal)?one:tow;
        //B2
        status[4]= (serial2.pinoutSignals()&QSerialPort::DataSetReadySignal)?one:tow;
        //D2
        //status[5]= (serial2.pinoutSignals()&QSerialPort::DataCarrierDetectSignal)?one:tow;

        //传递状态
        emit logicStatus(status,channel,model);
    }
}
